from typing import List, Union

from PyQt5.QtCore import Qt

from PyQt5.QtWidgets import QHBoxLayout, QTableWidget, QTableWidgetItem
from ..base import BaseExtendedWidget


class TableDisplay(BaseExtendedWidget):
    def __init__(self, layout_dir: str, title: List[str],
                 initial_value: List[List[Union[int, float, str]]]):
        super().__init__(layout_dir=layout_dir)
        self.char_width = 15
        self.on_check_callback = None
        self.title_list = title
        entryLayout = QHBoxLayout()
        entryLayout.setContentsMargins(0, 0, 0, 0)

        self.ctrl = QTableWidget()
        self.ctrl.verticalHeader().setVisible(False)
        self.ctrl.setMinimumWidth(500)

        # self.ctrl.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        for sublist in initial_value:
            assert len(sublist) == len(title)
        self.ctrl.setColumnCount(len(title))
        self.ctrl.setRowCount(len(initial_value))
        # self.ctrl.setMinimumHeight(len(initial_value) * self.ctrl.rowHeight(0) + 20)
        # self.ctrl.setMaximumHeight(len(initial_value) * self.ctrl.rowHeight(0) + 40)
        for i, text in enumerate(title):
            self.ctrl.setColumnWidth(i, len(text) * self.char_width + 10)
            self.ctrl.setHorizontalHeaderItem(i, QTableWidgetItem(text))

        self.central_layout.addLayout(entryLayout)
        entryLayout.addWidget(self.ctrl)

        self.set_value(initial_value)

    def check_data(self, value: List[List[Union[int, float, str]]]):
        for sublist in value:
            assert len(sublist) == len(self.title_list)

    def set_value(self, value: List[List[Union[int, float, str]]]):
        self.check_data(value)
        self.ctrl.setRowCount(len(value))
        for row, row_list in enumerate(value):
            for col, content in enumerate(row_list):
                if len(str(content)) * self.char_width > self.ctrl.columnWidth(col):
                    self.ctrl.setColumnWidth(col, len(str(content)) * self.char_width + 10)
                table_item = QTableWidgetItem(str(content))
                table_item.setTextAlignment(Qt.AlignCenter)
                self.ctrl.setItem(row, col, table_item)

    # def set_cell_value(self,row:int,col:int,value:Union[str,float,int]):
    #     self.ctrl.setItem(row,col, QTableWidgetItem(str(content)))
    def alert(self, alert_level: int):
        self.ctrl.alert(alert_level)
